package com.dongjiantong.app.controller.farmrecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.dto.FarmRecordsImmunizationDto;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsImmunization;
import com.dongjiantong.farmrecords.model.FarmRecordsImmunizationSub;
import com.dongjiantong.farmrecords.service.FarmRecordsImmunizationService;
import com.dongjiantong.farmrecords.service.FarmRecordsImmunizationSubService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.enums.AnimalTypeEnum;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 防疫中心-免疫记录表(养殖端)
 */

@Slf4j
@OpenBean
public class FarmRecordsImmunizationController {

    @Reference(version = "1.0.0")
    public FarmRecordsImmunizationService farmRecordsImmunizationService;
    @Reference(version = "1.0.0")
    public FarmRecordsImmunizationSubService farmRecordsImmunizationSubService;

    @Reference(version = "1.0.3")
    public AnimalTypeService animalTypeService;

    /**
     * 根据养殖场id,起止时间或者状态查询免疫记录 (条件都可以为空,表示查询所有)(包含对应免疫子表中的数据)
     * @param farmId  请求的养殖场id
     * @param fromDate 请求的查询开始时间
     * @param toDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @param breedSecondType 动物类型
     * @return  Response<PageInfo<FarmRecordsDisinfect>>
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","toDate","pageNum","pageSize","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsImmunization>> selectByFarmIdAndDate(
                                                                             @RequestParam(required = false) Long farmId,
                                                                             @RequestParam(required = false) String fromDate,
                                                                             @RequestParam(required = false) String toDate,
                                                                             @RequestParam(required = false) Integer pageNum,
                                                                             @RequestParam(required = false) Integer pageSize,
                                                                             @RequestParam(required = false) Integer breedSecondType){
        if (animalTypeService == null){
            throw new OPServerException("animalTypeService 服务为空,请检查");
        }
        if (farmRecordsImmunizationService == null){
            throw new OPServerException("请检查 farmRecordsImmunizationService 服务");
        }

        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }

        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());
        if (breedSecondType != null){
            map.put("breed_second_type",breedSecondType);
        }

        map.put("animal_second_non_bull",AnimalTypeEnum.BULL.getCode());

        PageInfo<FarmRecordsImmunization> farmRecordsImmunizationPageInfo = farmRecordsImmunizationService.selectByMapApp(pageNum,pageSize,map);
        return Response.ok(farmRecordsImmunizationPageInfo);
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsImmunization>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                       @RequestParam(required = false) Integer status,
                                                                       @RequestParam(required = false) Integer pageSize,
                                                                       @RequestParam(required = false) Integer pageNum){
        if (farmRecordsImmunizationService == null){
            throw new OPServerException("farmRecordsDisinfectService 服务为空,请重启服务后重试");
        }
        if (farmId == null){
            throw new OPServerException("养殖场id不能为空,请检查后重试");
        }

        if (pageSize == null){
            pageSize = 20;
        }
        if (pageNum == null){
            pageNum = 1;
        }

        //这里查询除牛之外的其他动物
        Integer nonBull = AnimalTypeEnum.BULL.getCode();

        PageInfo<FarmRecordsImmunization> farmRecordsImmunizationPageInfo = farmRecordsImmunizationService.selectListByStatus(pageNum,pageSize,status,farmId,nonBull);

        return Response.ok(farmRecordsImmunizationPageInfo);
    }

    /**
     * 根据免疫主表 主键id查询对应免疫记录
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsImmunizationDto> selectById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请求的id不能为空");
        }
        if (farmRecordsImmunizationService == null){
            throw new OPServerException("farmRecordsImmunizationService 为null,请检查");
        }
        FarmRecordsImmunizationDto farmRecordsImmunizationDto = farmRecordsImmunizationService.selectById(id);
        return Response.ok(farmRecordsImmunizationDto);
    }

    /**
     * 根据免疫子表id 查询一条免疫记录信息(即 首免或者二免,三免之类)
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.selectBySubId",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsImmunizationSub> selectBySubId(@RequestParam(required = false) Long id){
        if (id == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数id不能为空");
        }
        if (farmRecordsImmunizationService == null){
            throw new OPServerException("farmRecordsImmunizationService 为null,请检查");
        }
        FarmRecordsImmunizationSub farmRecordsImmunizationSub = farmRecordsImmunizationSubService.selectBySubId(id);
        if (farmRecordsImmunizationSub == null){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据");
        }
        return Response.ok(farmRecordsImmunizationSub);
    }

    /**
     * 新增一条免疫记录
     * @param farmRecordsImmunizationDto
     * @return long 返回插入免疫记录的id
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.createOne",
            paramNames = {"farmRecordsImmunizationDto","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> createOne(@RequestBody(required = false) FarmRecordsImmunizationDto farmRecordsImmunizationDto,
                                                  @RequestParam(required = false) Integer toStatus){
        if (farmRecordsImmunizationDto == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "请求参数对象不能为空");
        }
        if (farmRecordsImmunizationService == null){
            throw new OPServerException("farmRecordsImmunizationService 为null,请检查");
        }

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Map<String,Object> result = farmRecordsImmunizationService.createOne(loginInfo,farmRecordsImmunizationDto,toStatus);

        return Response.ok(result);
    }

    /**
     * 正常更新免疫记录(免疫主表 免疫子表)
     * @param farmRecordsImmunizationDto 请求的对象
     * @param toStatus
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.updateByIdOrNumber",
            paramNames = {"farmRecordsImmunizationDto","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> updateByIdOrNumber(@RequestBody (required = false) FarmRecordsImmunizationDto farmRecordsImmunizationDto,
                                                            @RequestParam(required = false) Integer toStatus){
        if (farmRecordsImmunizationService == null){
            throw new OPServerException("farmRecordsImmunizationService 为null,请检查");
        }
        if (farmRecordsImmunizationDto == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,HttpCode.BAD_REQUEST.getMessage());
        }

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Integer con = farmRecordsImmunizationService.updateByIdOrNumber(loginInfo,farmRecordsImmunizationDto,toStatus);

        Map<String,Object> map = Maps.newHashMap();
        if (con == 1) {
            map.put("updateResult","true");
        }else {
            map.put("updateResult","false");
        }

        return Response.ok(map);
    }

    /**
     * 更新免疫单据耳标号
     * 更新免疫记录(只更新免疫记录主表 耳标)
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsimmunization.updateEarNumber",
                            paramNames = {"farmRecordsImmunizationDto"},
                            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> updateEarNumber(FarmRecordsImmunizationDto farmRecordsImmunizationDto){
        Map<String,Object> map = Maps.newHashMap();
        boolean result = false;
        LoginInfo loginInfo = UserUtil.getCurrentUser();

        List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationDto.getVaccines();
        FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationDto.getImmunizationRecord();
        List<String> original_ear_list = farmRecordsImmunizationDto.getOriginal_ear();

        farmRecordsImmunizationService.updateByPrimaryKeySelective(farmRecordsImmunization);

        if (farmRecordsImmunizationSubList == null) {
            result = farmRecordsImmunizationService.updateEarNumber(loginInfo,farmRecordsImmunization,original_ear_list);
        }

        map.put("result",result);

        return Response.ok(map);
    }
}
